﻿var doc = $.load("testme.config");

// select node with xpath, return xmlnode array
var nodeList = doc.select("/config/list/*");
//console.log(nodeList);
//var nodeList = nodeList[0].select("prefix");

assert("return url nodeList", nodeList != null, true);
assert("return url nodeList > 0", nodeList.length > 0, true);

// change text value
nodeList[0].txt("text value");
console.log(nodeList[0].txt());

// change CDDATA value
nodeList[1].cddata("NEW CDDATA");
console.log(nodeList[1].cddata());

// change attribute
nodeList[0].attr("id", "new id");
console.log(nodeList[0].attr("id"));

// add attribute
nodeList[0].attr("name", "new name");
console.log(nodeList[0].attr("name"));

var item = nodeList[0].parent();

// add new text node
var element = $.create("prefix");
element.txt("NEW ELEMENT WITH TXT VALUE");
item.append(element);

// add new CDDATA node
element = $.create("prefix", "NEW ELEMENT WITH CDDATA");
element.attr("id", "CDDATA");
item.append(element);

// add new text node before selected node
var element1 = $.create("prefix");
element1.txt("before node ID=CDDATA");
item.insertBefore(element1, element);

// add new text node after selected node
var element2 = $.create("prefix");
element2.txt("after node ID=CDDATA");
item.insertAfter(element2, element);

// delete node
var findItem = nodeList.find(function (e, i) {
    if (e.txt().toLowerCase() == "http://google.com") {
        return true;
    } else {
        return false;
    }
});

if (findItem) {
    // remove xml node
    item.remove(findItem);
} else {
    console.error('node not found: "http://google.com"');
}

nodeList.each(function (e, i) {
    //e.txt(e.txt() + i);
});

// save xml file
doc.save();
console.pause();